package org.now.ypos.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;

import java.util.Objects;

/**
 * ApplicationContextHolder
 * provide getBean method from application context
 *
 * @author wl
 * @since 2020.11.10
 */
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public final void setApplicationContext(@NonNull final ApplicationContext applicationContext) {
        synchronized (this) {
            if (Objects.isNull(ApplicationContextHolder.applicationContext)) {
                ApplicationContextHolder.applicationContext = applicationContext;
            }
        }
    }

    /**
     * Get bean by name and type
     *
     * @param name  component name
     * @param clazz class type
     * @param <T>   specific type
     * @return component in application context
     */
    public static <T> T getBean(final String name, final Class<T> clazz) {
        return applicationContext.getBean(name, clazz);
    }

    /**
     * Get bean by type
     *
     * @param clazz class type
     * @param <T>   specific type
     * @return component in application context
     */
    public static <T> T getBean(final Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }
}
